var prefix = ctx + "msg/messages";
var deptRows = []
var userRows = []
var roleRows = []
var isIE8 = false;
$(function() {
	var userAgent = navigator.userAgent;
	var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; 
	var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
	if(isIE && fIEVersion == 8) {
		isIE8 = true
    }
	
	$('#msgContent').summernote({ 
		placeholder: isIE8?'':'请输入消息内容', 
		height: 200,
		toolbar: [
		    ['style', ['style']],
		    ['font', ['bold', 'italic', 'underline', 'clear']],
		    ['fontname', ['fontname']],
		    ['color', ['color']],
		    ['para', ['ul', 'ol', 'paragraph']],
		    ['table', ['table']],
//		    ['insert', ['link', 'picture', 'hr']],
//		    ['view', ['fullscreen', 'codeview']],
//		    ['help', ['help']]
		  ],
		});
    //判断是新增还是修改
    if($("#oper").val() === 'edit'||$("#oper").val() === 'view') {
        initFields(message)
    }

    if($("#oper").val() === 'view') {
        forbiddenPage()
    }

     var range = $('input[name="receiveRange"]:checked').val();
     receiverRange(range)
     $('input[name="receiveRange"]').on('ifChecked',
         function(event) {
         var range = $(event.target).val();
             receiverRange(range);
      });
    jQuery.validator.addMethod("isAddContent", function (value, element) {
        return !($(element).summernote('isEmpty'));
    },"消息内容必须填写");
    jQuery.validator.addMethod("limitLength", function (value, element) {
    	var str = $(element).summernote('code').replace(/<.*?>/g,"").replace(/&nbsp;/ig, "")
        return !(str.length > 1000);
    },"消息内容不得超过1000字");
    jQuery.validator.addMethod("isCheckChannel", function (value, element) {
        return $('input[name=msgChannels]:checked').length > 0;
    },"至少选择一种发送方式");
    jQuery.validator.addMethod("receiverObject", function (value, element) {
        if($("input[name=receiveRange]:checked").val() === '2' ) {
            return true
        }
        if(deptRows.length === 0 && userRows.length === 0 && roleRows.length === 0) {
            return false
        }
        return true
    },"至少选择一个接受对象");

    $("#editForm").validate({
        onkeyup : false,
        ignore: [],
        rules : {
            type : {
                required : true
            },
            msgTitle : {
                required : true
            },
            msgContent : {
                isAddContent:true,
                limitLength: true,
            },
            msgChannels:{
                isCheckChannel:true
            },
            receiveRange : {
                required : true
            },
            receiverObject: {
                receiverObject: true
            }
        },
        messages : {
            type : {
                required : "请选择消息类型",
            },
            msgTitle : {
                required : "请输入消息标题",
            },
            receiveRange : {
                required : "请选择接收范围"
            },
            msgContent: {
                required: "消息内容必须填写"
            }
        },
        errorPlacement : function(error, element) {
            if (element.is(':radio') || element.is(':checkbox')) { // 如果是radio或checkbox
                var eid = element.attr('name'); // 获取元素的name属性
                error.appendTo(element.parent()); // 将错误信息添加当前元素的父结点后面
            } else if(element.is("textarea")) {
                error.appendTo(element.parent().find("#validate-result"));
            }else if(element[0]['name']==='receiverObject') {
                error.appendTo(element.parent().find("#validate-result-object"));
            }else {
                error.insertAfter(element);
            }
        },
        focusCleanup : true
    });
});


function forbiddenPage() {

    //隐藏文本框
    $("#editForm").find("input[type=text],textarea").prop("readonly",true)

    //只读单选,复选,下拉
    $("#editForm").find("select,input[type=checkbox],input[type=radio]").prop("disabled","disabled")

    //只读文本编辑器
    $('#msgContent').summernote('disable');

    //提交按钮隐藏
    $("#submit-area").hide()

    //隐藏选择
    $("#receive-table").find("a").attr("hidden","hidden")
}

function initFields(data) {
    //给富文本编辑器设置值
    if(data.msgContent) {
        $("#msgContent").summernote("code",data.msgContent)
    }
    if(data.sysMsgRecievers) {
        userRows = data.sysMsgRecievers
    }
    if(data.sysMsgRoles) {
        roleRows = data.sysMsgRoles
    }
    if(data.sysMsgDepts) {
        deptRows = data.sysMsgDepts
    }
    formatSr()
    if(data.sendChannel) {
        var channels = data.sendChannel.split(",");
        $.each($('input[name=msgChannels]'),function () {
            var temp = $(this).val().toString()
            if(channels.indexOf(temp) >= 0) {
                $(this).prop("checked",true)
                $(this).parent().addClass("checked")
            }
        })
    }
}

function receiverRange(receiverRange) {
     if (receiverRange === "1") {
          $("#receive-object").parents(".form-group").show();
         $("#receive-object").find("label").addClass("is-required")
     } else if (receiverRange === "2") {
          $("#receive-object").parents(".form-group").hide();
         $("#receive-object").find("label").removeClass("is-required")
     }
}
function submitHandler() {
	var strContent = $("#msgContent").summernote("code").replace(/<.*?>/g,"").replace(/&nbsp;/ig, "")
	//ie8校验消息内容必填
	if (isIE8){
		if	(!(strContent.length)){
			$("#validate-result").text('消息内容必须填写')
			return false;
		}else if(strContent.length>100){
			$("#validate-result").text('消息内容不得超过1000字')
			return false;
		}else{
			$("#validate-result").text('')
		}
	}

     if ($.validate.form()) {
         var channels = []
         $.each($('input[name=msgChannels]:checked'),function () {
             channels.push($(this).val())
         })
         var data = {
             msgType: $("#type").val(),
             msgTitle: $("#msgTitle").val(),
             msgContent: $("#msgContent").summernote("code"),
             sendChannels: channels,
             sendType: "1",
             receiveRange: $("input[name=receiveRange]:checked").val(),
             sysMsgRecievers: userRows,
             sysMsgDepts: deptRows,
             sysMsgRoles: roleRows
         }
         if($("#oper").val() === 'edit') {
             data.msgId = $("#msgId").val()
         }
         
         var option = {
             url:prefix,
             type: $("#oper").val()=='edit'?'PUT':'POST',
             data: JSON.stringify(data),
             contentType: 'application/json',
             dataType: "json",
             beforeSend: function () {
                 $.modal.loading("正在保存中，请稍后...");
             },
             success: function(result) {
                 $.modal.closeLoading()
                 if(result.code === 0) {
                     var topWindow = $(window.parent.document);
                     var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-panel');
                     var $contentWindow = $('.RuoYi_iframe[data-id="' + currentId + '"]', topWindow)[0].contentWindow;
                     $.modal.close();
                     $contentWindow.$.modal.msgSuccess(result.msg==null?'操作成功':result.msg);
                     $contentWindow.$(".layui-layer-padding").removeAttr("style");
                     if ($contentWindow.table.options.type == table_type.bootstrapTable) {
                         $contentWindow.$.table.refresh();
                     } else if ($contentWindow.table.options.type == table_type.bootstrapTreeTable) {
                         $contentWindow.$.treeTable.refresh();
                     }
                     $.modal.closeMessageTab();
                 }else {
                     $.modal.alertError(result.msg)
                 }
             }
         }
         $.ajax(option)
     }
}

function selectDept() {
    var url = prefix + '/selectDept';
    var options = {
        title: '选择部门',
        url: url,
        callBack: doSubmit
    };
    var deptIds = []
    deptRows.forEach(function (dept) {
        deptIds.push(dept.deptId)
    })

    $.modal.openOptionsInitData(options,deptIds);
}
function selectRole() {
    var url = prefix + '/selectRole';
    var options = {
        title: '选择角色',
        url: url,
        callBack: doSubmitRole
    };
    var roleIds = []
    roleRows.forEach(function (role) {
        roleIds.push(role.roleId)
    })
    $.modal.openOptionsInitData(options,roleIds);
}

function selectUser() {
    var url = prefix + '/selectUser';
    var options = {
        title: '选择用户',
        url: url,
        callBack: doSubmitUser
    };
    var userIds = []
    userRows.forEach(function (user) {
        userIds.push(user.receiverUserId)
    })
    $.modal.openOptionsInitData(options,userIds);
}

function doSubmit(index, layero) {
	var rows = layero.find('iframe')[0].contentWindow.$._tree.getCheckedNodes()
    deptRows = []
    rows.forEach(function(row) {
        deptRows.push({
            deptName: row.name,
            deptId: row.id
        })
    })
    formatSr()
    layer.close(index);
}
function doSubmitRole(index, layero){
    var iframeWin = window[layero.find('iframe')[0]['name']];
    var rows = iframeWin.$('#bootstrap-table').bootstrapTable('getSelections');
    roleRows = []
    rows.forEach(function(row) {
        roleRows.push({
            roleId: row.roleId,
            roleName: row.roleName
        })
    })
    formatSr()
    layer.close(index);
}
function doSubmitUser(index, layero){
    var iframeWin = window[layero.find('iframe')[0]['name']];
    var rows = iframeWin.$('#bootstrap-table').bootstrapTable('getSelections');
    var currentUser = []
    userRows = []
    rows.forEach(function(row) {
        currentUser.push(row.username)
        userRows.push({
            receiverUserId: row.userId,
            receiverUserName: row.username
        })
    })
    formatSr()
    layer.close(index);
}

function formatSr() {
    var deptTemp = []
    deptRows.forEach(function (dept) {
        deptTemp.push(dept.name || dept.deptName)
    })
    var userTemp = []
    userRows.forEach(function (user) {
        userTemp.push(user.username||user.receiverUserName)
    })
    var roleTemp = []
    roleRows.forEach(function (role) {
        roleTemp.push(role.roleName)
    })
    $("#current-user").html(userTemp.length == 0?"未选择":userTemp.join(","))
    $("#current-dept").html(deptTemp.length == 0?"未选择":deptTemp.join(","))
    $("#current-role").html(roleTemp .length == 0?"未选择":roleTemp.join(","))
}
$("input[name='createTime']").datetimepicker({
     format: "yyyy-mm-dd",
     minView: "month",
     autoclose: true
});

$("input[name='updateTime']").datetimepicker({
     format: "yyyy-mm-dd",
     minView: "month",
     autoclose: true
});
